import { getItemMangae } from "../系统功能/GlobalObjectManage";
import { ChanceData, MaxChanceNum, MoneyEnum, MoneyName, PriceData, PriceType } from "../配置/基础配置";
import { randomInRange } from "./utls";

export function readStrFromFile(path: string): string {
    let json = '';
    let AList: TStringList;
    //TStrings访问文本文件的方式：
    AList = GameLib.CreateStringList()

    let newPath = `${GameLib.Path}${path}`
    try {
        //出于对版本使用者机器的保护出发(非开发者),引擎中的脚本读写只允许Mir200\Envir目录下的文件,Gamelib.EnvirPath可以取得
        if (GameLib.FileExists(newPath)) { //如果文件存在
            AList.LoadFromFile(newPath); //加载文件
            // console.log(AList.GetStrings(3))
            json = AList.Text;
            // for (let i = 0; i < AList.Count; i++) {
            //     let str = AList.GetStrings(i);
            //     json += `${str}\n`;
            // }
        }
    } finally {
        AList.Free()
    }
    return json;
}

export function saveStrToFile(path: string, str: string): void {
    let newPath = `${GameLib.Path}${path}`
    let root = newPath.substring(0, newPath.lastIndexOf('\\'));
    GameLib.ForceDirectories(root)
    //TStrings访问文本文件的方式：
    let AList: TStringList = GameLib.CreateStringList()
    try {
        AList.Add(str);
        AList.SaveToFile(newPath);
    }
    finally {
        AList.Free;
    }
}

export function deleteFile(path: string) {
    let newPath = `${GameLib.Path}${path}`
    GameLib.DeleteFile(newPath);
}

//获取主人
export function getMaster(actor: TActor): TActor {
    let master = actor.GetMaster()
    if (master) {
        return master
    }
    return actor;
}


/**
 * 
 * @param sorce 移动的目标
 * @param mapId 地图
 * @param mapx 中心点坐标
 * @param mapy 
 * @param range1 随机的范围r range1<=r<=range2
 * @param range2  如果不传range2 范围r 0<=r<=range1
 */
export function randomMoveInRange(sorce: TActor, map: TEnvirnoment, mapx: number, mapy: number, range1: number, range2?: number): void {
    if (!range2) {
        range2 = range1;
        range1 = 0;
    }
    let list = [];
    for (let i = -range2; i <= range2; i++) {
        let ii = Math.abs(i);
        for (let j = -range2; j <= range2; j++) {
            let jj = Math.abs(j);
            if (ii < range1 && jj < range1) {
                continue;
            }
            let newx = mapx + i;
            let newy = mapy + i;
            if (map.CanMove(newx, newy, true)) {
                list.push({
                    x: newx,
                    y: newy,
                })
            }
        }
    }
    if (list.length > 0) {
        let index = randomInRange(list.length);
        let item = list[index];
        sorce.Move(map.MapID, item.x, item.y);
    }
}


export const LineHeight = 15;


export interface ShowStringData {
    name: string,
    fucName?: string,
    hint?: string,
    showImg?: boolean,
}
/**
 * 
 * @param showNameList 显示的文字列表
 * @param fucNameList 响应的函数列表
 * @param adrX x轴增加位置 默认60
 * @param adry y轴增加位置 默认15
 * @param lineNum  一行几个
 * @returns 
 */
export function getShowString(showNameList: Array<ShowStringData>, px?: number, py?: number,
    adrX?: number, adry?: number, lineNum?: number) {
    adrX = adrX || 80
    adry = adry || 15
    px = px || 0
    py = py || 0
    lineNum = lineNum || 4
    let ItemsString = '';
    for (let i = 0; i < showNameList.length; i++) {
        let x = (i % lineNum) * adrX + px
        let y = Math.floor(i / lineNum) * adry + py
        let name = showNameList[i].name
        let fucName = showNameList[i].fucName || ''
        let hint = showNameList[i].hint || ''
        let showImg = showNameList[i].showImg || false
        if (showImg) {
            ItemsString += `{E=${name};X=${x};Y=${y};}`
            x += 35;
        }
        ItemsString += `<{S=${name};C=251;Hint=${hint};X=${x};Y=${y};}/@${fucName}>`
    }
    return ItemsString
}

/**
 * 根据价格数据生成显示文件
 * @param price 价格列表
 * @param addx  偏移x
 * @param addy 偏移y
 * @param lineHeight 每行高度
 * @returns 
 */
export function getPriceString(price: Array<PriceData>, addx?: number, addy?: number, lineHeight?: number): any {
    let str = "";
    addx = addx || 0
    addy = addy || 0
    lineHeight = lineHeight || LineHeight
    let y = addy
    for (let i = 0; i < price.length; i++) {
        let item: PriceData = price[i];

        if (item.type === PriceType.Money) {
            let noneyName = MoneyName[<number>item.name];
            str += `<{S=${noneyName}:${item.num}个;C=255;X=${addx};Y=${y}}>`
        }
        else if (item.type === PriceType.Item) {
            let array: Array<string>
            let type = typeof (item.name)
            if (type === "string" || type === "number") {
                array = [`${item.name}`];
            }
            else {
                array = item.name as Array<string>;
            }
            let tmpStr = array.join(",")
            str += `<{S=[${tmpStr}]:${item.num}个;C=255;X=${addx};Y=${y}}>`
        }
        else {
            let index = <number>item.name;
            let name = getItemMangae().getLvNameByIndex(index);
            str += `<{S=${name}:${item.num}个;C=255;X=${addx};Y=${y}}>`
        }
        y += LineHeight;
    }


    return { str, y }
}


//物品是否重叠
function isOverlapItem(item: TUserItem) {
    return [0, 1, 3, 42, 71].includes(item.StdMode);
}

//获取物品数量
function getItemNum(item: TUserItem) {
    if (isOverlapItem(item)) {
        return item.Dura
    }
    return 1;
}

/**
 * 检查人物需要有足够的需求物品
 * @param price 
 * @param play 
 */
export function checkPriceList(price: Array<PriceData>, play: TPlayObject, customItemList?: Array<number>): boolean {
    for (let i = 0; i < price.length; i++) {
        let item: PriceData = price[i];
        if (item.type === PriceType.Money) {
            let moneyType: MoneyEnum = item.name as MoneyEnum;
            if (!play.CanTakeGameMoney(moneyType, item.num)) {
                return false;
            }
        }
        else {
            let list: Array<string> = null
            if (item.type === PriceType.Item) {
                if (item.name instanceof String || item.name instanceof Number) {
                    list = [`${item.name}`];
                }
                else {
                    list = item.name as Array<string>;
                }
            }
            else {
                let index = <number>item.name;
                list = getItemMangae().getItemLvList2(index);
            }
            let num = 0;
            let flag = false;
            for (let i = play.MaxBagSize - 1; i >= 0; i--) //循环背包
            {
                let AItem: TUserItem = play.GetBagItem(i); //取出一个背包物品 
                if (AItem) {
                    //物品在OK框不计算
                    if (customItemList && customItemList.includes(AItem.MakeIndex)) {
                        continue
                    }
                    if (list.includes(AItem.Name)) {
                        num += getItemNum(AItem);
                        if (num >= item.num) {
                            flag = true;
                            break;
                        }
                    }
                }
            }
            if (!flag) {
                return false
            }
        }
    }
    return true
}

/**
 * 拿走人物需要有足够的需求物品
 * @param price 
 * @param play 
 */
export function takePriceList(price: Array<PriceData>, play: TPlayObject, opt: string, showTs = true, customItemList?: Array<number>): boolean {

    if (!checkPriceList(price, play, customItemList)) {
        if (showTs) {
            play.MessageBox("你没有足够的货币或者物品")
        }
        return false;
    }
    for (let i = 0; i < price.length; i++) {
        let item: PriceData = price[i];
        if (item.type === PriceType.Money) {
            let moneyType: MoneyEnum = item.name as MoneyEnum;
            if (play.CanTakeGameMoney(moneyType, item.num)) {
                play.TakeGameMoney(moneyType, item.num, opt)
            }
        }
        else {
            let list: Array<string> = null
            if (item.type === PriceType.Item) {
                if (item.name instanceof String || item.name instanceof Number) {
                    list = [`${item.name}`];
                }
                else {
                    list = item.name as Array<string>;
                }
            }
            else {
                let index = <number>item.name;
                list = getItemMangae().getItemLvList2(index);
            }
            let num = item.num;
            for (let i = play.MaxBagSize - 1; i >= 0; i--) //循环背包
            {
                let AItem: TUserItem = play.GetBagItem(i); //取出一个背包物品 
                if (AItem) {
                    //物品在OK框不计算
                    if (customItemList && customItemList.includes(AItem.MakeIndex)) {
                        continue
                    }
                    if (list.includes(AItem.Name)) {
                        let itemNum = getItemNum(AItem)
                        if (itemNum < num) {
                            play.DeleteBagItem(AItem, itemNum)
                            num -= itemNum
                        }
                        else {
                            play.DeleteBagItem(AItem, num)
                            num = 0
                            break;
                        }
                    }
                }
            }
        }
    }
    return true
}

/**
 * 拿走人物物品
 * @param play 人物
 * @param itemName 物品名称 或者名称数组
 * @param num 数量
 * @param opt 操作方式
 * @returns 
 */
export function takeItem(play: TPlayObject, itemName: string | Array<string>, num: number, opt: string, showTs?: boolean): boolean {
    let price: PriceData = {} as PriceData;
    price.type = PriceType.Item;
    price.name = itemName
    price.num = num;
    return takePriceList([price], play, opt, showTs)
}

/**
 * 拿走人物货币
 * @param play 人物
 * @param moneyType 货币类型
 * @param num 数量
 * @param opt 操作方式
 * @returns 
 */
export function typeMoney(play: TPlayObject, moneyType: MoneyEnum, num: number, opt: string, showTs?: boolean) {
    let price: PriceData = {} as PriceData;
    price.type = PriceType.Money;
    price.name = moneyType
    price.num = num;
    return takePriceList([price], play, opt, showTs)

}
//获取随机配置值
export function getChanceResult(chanceList: Array<ChanceData>): number {
    if (!chanceList || chanceList.length === 0) {
        return 0
    }
    let chance = randomInRange(MaxChanceNum);
    for (let i = 0; i < chanceList.length; i++) {
        let item = chanceList[i];
        if (item.chance > chance) {
            let result: number = randomInRange(item.min, item.max + 1);
            return result;
        }
    }
    return 0;
}

//检查actor是否存活
export function checkActor(actor: TActor) {
    if (!actor || actor.Death || actor.Ghost) {
        return false;
    }

    return true
}

//获取OK框物品对象
export function getCustomItemList(play: TPlayObject, count?: number): Array<number> {
    count = count || 1;
    let array: Array<number> = new Array<number>();
    for (let i = 0; i < count; i++) {
        let item: TUserItem = play.GetCustomItem(i)
        if (item) {
            array.push(item.MakeIndex)
        }
    }
    return array;

}